package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.IApArticleRepository;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IArticleStaticUrl;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author WSJ
 * @Date 2022-03-15-16:35
 * @Version 1.0 （版本号）
 */
@Service
public class ArticleStaticUrlImpl implements IArticleStaticUrl {
    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private IApArticleRepository repository;

    @Override
    @Async
    public void createStaticUrl(ApArticle apArticle, String content) {
        try {
            //获取模板
            Template template = configuration.getTemplate("article.ftl");
            StringWriter out = new StringWriter();
            //定义数据模型
            Map<String, Object> date = new HashMap<>();
            date.put("content",JSON.parseArray(content));
            //合并数据和模板
            template.process(date,out);
            //上传到minio
            InputStream input=new ByteArrayInputStream(out.toString().getBytes());
            String url = minIOService.upload(apArticle.getId() + ".html", input, "text/html");
            //设置静态地址
            apArticle.setStaticUrl(url);
            apArticleService.updateById(apArticle);
            //保存文章到es
            ApArticleSearch search = new ApArticleSearch();
            BeanUtils.copyProperties(apArticle, search);
            repository.save(search);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
